/*================================================================
*   Copyright (C) 2023 baichao All rights reserved.
*
*   文件名称：mmap.c
*   创 建 者：baichao
*   创建日期：2023年10月16日
*   描    述：
*
================================================================*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>

typedef struct
{
    char name[4];
    int age;
} people;

int main(int argc, char **argv)
{
    int fd, i;
    people *p_map;
    char temp;
    fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 00777);
    lseek(fd, sizeof(people) * 5, SEEK_SET);
    write(fd, "", 1);

    p_map = (people *)mmap(NULL, sizeof(people) * 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (p_map == (void *)-1)
    {
        fprintf(stderr, "mmap: %s \n", strerror(errno));
        return -1;
    }

    close(fd);

#ifdef _MPROTECT_
    // 将该内存区域所在的页面设置为只读
    if (mprotect(p_map, sizeof(people) * 10, PROT_READ) == -1) {
        perror("mprotect");
        exit(1);
    }
#endif

    temp = 'a';
    for (i = 0; i < 10; i++, temp++)
    {
        (*(p_map + i)).name[1] = '\0';
        memcpy((p_map + i)->name, &temp, 1);
        (p_map + i)->age = 30 + i;
    }
    printf("Initialize.\n");
    sleep(15);
    munmap(p_map, sizeof(people) * 10);
    printf("UMA OK.\n");
    return 0;
}
